<template>
  <div>
    <a-upload
      :action="uploadAction"
      :headers="headers"
      :data="{ path: bizPath }"
      :list-type="listType"
      :accept="accept"
      :file-list="fileList"
      :disabled="disabled"
      :beforeUpload="beforeUpload"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < maxLength">
        <a-icon :type="uploadLoading ? 'loading' : 'plus'" v-if="listType==='picture-card'" />
        <a-button v-else style="margin-top:28px"> <a-icon type="upload" /> 上传 </a-button>
        <div class="ant-upload-text">{{ text }}</div>
      </div>
    </a-upload>
    <div v-if="tip" class="tip" v-html="tip">{{ tip }}</div>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFileAccessHttpUrl } from '@/api/manage'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    const reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
    return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'JImageUpload',
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      uploadLoading: false,
      picUrl: false,
      headers: {},
      fileList: [],
      errImg: '',
    }
  },
  props: {
    listType:{
      type:String,
      default: 'picture-card',
    },
    uploadSize: {
      type: Number,
      default: 10,
    },
    maxLength: {
      type: Number,
      default: 8,
    },
    imgStyle: {
      type: String,
      default: () => {
        return 'height:104px;max-width:300px'
      },
    },
    tip: {
      type: String,
      required: false,
      default: '',
    },
    text: {
      type: String,
      required: false,
      default: '上传',
    },
    /* 这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: 'temp',
    },
    //上传类型
    accept: {
      type: String,
      required: false,
      default: '.jpg, .png, .jpeg',
    },
    // acceptList: {
    //   type: Array,
    //   required: false,
    //   default: ['image/jpeg', 'image/jpg', 'image/png'],
    // },
    value: {
      type: [String, Array],
      required: false,
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    isMultiple: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  watch: {
    value(val) {
      if (val instanceof Array) {
        this.initFileList(val.join(','))
      } else {
        this.initFileList(val)
      }
      if (!val || val.length == 0) {
        this.picUrl = false
      }
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
  },
  methods: {
    getFileAccessHttpUrl(avatar, subStr) {
      if (!subStr) subStr = 'http'
      if (avatar && avatar.startsWith(subStr)) {
        return avatar
      } else {
        if (avatar &&　avatar.length > 0 && avatar.indexOf('[') == -1) {
          return window._CONFIG['domainName'] + '/' + avatar
        }
      }
    },
    initFileList(paths) {
      if (!paths || paths.length == 0) {
        this.fileList = []
        return
      }
      this.picUrl = true
      const fileList = []
      const arr = paths.split(',')
      for (var a = 0; a < arr.length; a++) {
        const url = getFileAccessHttpUrl(arr[a])
        fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: 'done',
          url: url,
          response: {
            status: 'history',
            message: arr[a]
          }
        })
      }
      this.fileList = fileList
    },
    beforeUpload: function (file) {
      console.log(file.type)
      // const isJpgOrPng = this.acceptList.includes(file.type);
      // // var fileType = file.type
      // // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      // if (!isJpgOrPng) {
      //   this.errImg = file
      //   this.$message.error(`请上传${this.accept}格式图片!`)
      //   return false
      // }
      // if (fileType.indexOf('image') < 0) {
      //   this.$message.warning('请上传图片')
      //   return false
      // }
      const isLt2M = file.size / 1024 / 1024 < this.uploadSize
      if (!isLt2M) {
        this.errImg = file
        this.$message.error('上传图片大小不能超过' + this.uploadSize + 'MB!')
      }
      // return isJpgOrPng && isLt2M
      return isLt2M
    },
    handleChange(info) {
      this.picUrl = false
      let fileList = info.fileList
      const findIndex = info.fileList.findIndex((item) => item.uid === this.errImg.uid)
      if (findIndex > -1) {
        fileList.splice(findIndex, 1)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.picUrl = true
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.message
            }
            return file
          })
        }
        // this.$message.success(`${info.file.name} 上传成功!`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      } else if (info.file.status === 'removed') {
        this.handleDelete(info.file)
      }
      this.fileList = fileList
      if (info.file.status === 'done' || info.file.status === 'removed') {
        this.handlePathChange()
      }
    },
    // 预览
    handlePreview(file) {
      console.log(file);
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    getAvatarView() {
      if (this.fileList.length > 0) {
        const url = this.fileList[0].url
        return this.getFileAccessHttpUrl(url)
      }
    },
    handlePathChange() {
      const uploadFiles = this.fileList
      let path = ''
      if (!uploadFiles || uploadFiles.length == 0) {
        path = ''
      }
      const arr = []
      if (!this.isMultiple) {
        arr.push(uploadFiles[uploadFiles.length - 1].response.message)
      } else {
        for (var a = 0; a < uploadFiles.length; a++) {
          arr.push(uploadFiles[a].response.message)
        }
      }
      if (arr.length > 0) {
        path = arr.join(',')
      }
      this.$emit('change', path)
    },
    handleDelete(file) {
      // 如有需要新增 删除逻辑
      console.log(file)
    },
    handleCancel() {
      this.close()
      this.previewVisible = false
    },
    close() {},
  },
  model: {
    prop: 'value',
    event: 'change',
  },
}
</script>

<style scoped lang="less">
/deep/.ant-upload-list ant-upload-list-picture{
  .ant-upload-list-picture .ant-upload-list-item, .ant-upload-list-picture-card .ant-upload-list-item{
    float: left;
    width: 200px !important;
    margin-right: 8px;
  }
}
/deep/.ant-upload{
  position: relative;
.show-p-name{
      position: absolute;
    top: 100%;
    left: 50%;
    transform: translate(-50%);
}
}

.tip {
  font-size: 12px;
  font-weight: 400;
  color: #888888;
  line-height: 20px;
  margin: 10px 0 6px;
}
</style>
